<template>
  <div>
    <!--  顶部面包屑  -->
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回
      </el-button>
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}
        </el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/invoice/Entering/toSubmit' }"
          >发票管理
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{
            path: '/invoice/Entering/toSubmit'
          }"
          >发票录入
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb">新增</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs v-model="activeName" class="el-tabs__customize">
          <el-tab-pane label="基本信息" name="a">
            <!-- <keep-alive> -->
            <basicInfo
              class="commonClass"
              ref="basicInfo"
              :form="basicForm"
              @settlementCoder="settlementCoder"
              @basicGetDate="basicGetDate"
              @clearTable="clearTable"
            ></basicInfo>
            <!-- </keep-alive> -->
          </el-tab-pane>

          <el-tab-pane label="发票清单" name="b">
            <invoiceTableBill
              class="commonClass"
              ref="invoiceBillList"
              :tableBill="invoiceBillList"
              :basicForm="basicForm"
              @fixMoney="fixMoney"
              @businessType="businessType"
              :codeer="codeer"
              :isAdd="isAdd"
              :businessValue="businessValue"
            />
          </el-tab-pane>
          <el-tab-pane label="款项明细" name="c">
            <payment-details class="commonClass" ref="paymentDetails"></payment-details>
          </el-tab-pane>
          <el-tab-pane label="发票信息" name="d">
            <invoiceTableInfo class="commonClass" ref="invoiceInfoList" />
          </el-tab-pane>
          <el-tab-pane label="附件" name="e">
            <attachment
              ref="attachment"
              :parentData="fileList"
              class="commonClass"
            ></attachment>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button type="bottom" icon="icon-ccui-save" @click="timekeep()"
            >暂存
          </el-button>
        </li>
        <li
          v-if="
            $route.query.enterStatus == '' ||
              $route.query.enterStatus == '2' ||
              $route.query.enterStatus == '6'
          "
        >
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('save')"
            >保存并校验
          </el-button>
        </li>
        <li
          v-if="
            $route.query.enterStatus == '' ||
              $route.query.enterStatus == '2' ||
              $route.query.enterStatus == '6'
          "
        >
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('submit')"
            >保存并提交
          </el-button>
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-reject"
            v-if="$route.query.enterStatus == '3'"
          >
            撤回
          </el-button>
        </li>
        <div class="ccui-bottom-guide-divider" />
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回
          </el-button>
        </li>
      </ul>
    </el-bottom-guide>
    <!-- <el-bottom-guide >
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            >撤回
          </el-button>
        </li>
        <li>
            <el-button
            type="bottom"
            icon="icon-ccui-return"
            >返回
          </el-button>
        </li>
      </ul>
    </el-bottom-guide> -->
  </div>
</template>

<script>
import basicInfo from "../components/basicInfo";
import invoiceTableBill from "../components/invoiceTableBill";
import invoiceTableInfo from "../components/invoiceTableInfo";
import paymentDetails from "../components/paymentDetails";
import attachment from "@/basa/components/public/uploadInfo2";
import { ishasAgentId } from "@/basa/utils";
import { saveInvoceBasic, submitInvoice, tempSaveInvoceBasic } from "../api";

export default {
  name: "invoice_add",
  components: {
    basicInfo,
    invoiceTableBill,
    invoiceTableInfo,
    attachment,
    paymentDetails
  },
  data() {
    return {
      basicForm: {
        reportInOrgName: "", //
        partyBName: "",
        invoiceCode: "",
        invoiceName: "",
        settlementCode: "",
        settlementName: "",
        categoryName: "",
        currency: "",
        settlementAmount: "",
        totalInvoiceAmount: "",
        currentInvoiceAmount: "",
        invoiceNum: "",
        compileUser: "",
        compileDate: new Date(),
        remark: "",
        contractCode: "", //合同编号
        contractName: "", //合同名称
        amountExcludeTax: "",
        tax: "",
        amount: "",
        invoicetype: "",
        departId: "", // 部门id
        departName: "", // 部门名称
        departCode: "", // 部门4A编码
        accountingOrganId: "", // 核算组织id
        accountingOrgan: "", // 核算组织名称
        accountingOrganCode: "", // 核算组织code
        projectName:'',//项目名称
        projectCode:'',//项目名称编码
        standardMoney:'模拟数据',//本位币
        standardMoneyCode:'01',//本位币编码
        businessTypeName:'采购入库',//业务类型
      },
      invoiceBillList: [],
      invoiceInfoList: [],
      fileList: [],
      activeName: "a",
      submitFlag: false, // 缓存
      showMessage: "",
      codeer: "",
      fileData: [],
      isAdd: true,
      businessValue: "",
      basicFormDate: ""
    };
  },
  methods: {
    clearTable() {
      this.invoiceBillList = [];
      // this.invoiceInfoList= []
      this.fileList = [];
    },
    fixMoney(data) {
      this.showMessage = data;
    },
    businessType(data) {
      this.businessValue = data;
    },
    settlementCoder(data) {
      console.log("settlementCoder>>>>", data);
      if (this.codeer !== data) {
        this.invoiceBillList = [];
        // this.$refs.invoiceInfoList.tableData=[];
        this.codeer = data;
      }
    },
    timekeep() {
      this.$refs.basicInfo.form.compileDate = this.basicFormDate; //时间重新赋值

      this.$refs.invoiceInfoList.tableData.forEach(e => {
        if (typeof e.id == "string") {
          delete e.id;
        }
      });

      this.$refs.invoiceBillList.tableData.forEach((e, index) => {
        e.sn = index;
        e.rate = e.taxRate;
        e.settlementListId = e.id;
      });
      let arrNum = this.$refs.attachment.fileList.length;
      for (let i = 0; i < arrNum; i++) {
        this.fileData[i] = {};
        this.fileData[i].uploadTime = this.$refs.attachment.fileList[
          i
        ].createTime;
        this.fileData[i].uploadId = this.$refs.attachment.fileList[i].uploadId;
        this.fileData[i].fileDesc = this.$refs.attachment.fileList[i].fileDesc;
      }
      this.$refs.paymentDetails.tableData.forEach(e=>{
        if(typeof e.id == 'string'){
          delete e.id;
        }
      })
      var obj = {
        invoceBasic: this.$refs.basicInfo.form,
        invoceBill: this.$refs.invoiceBillList.tableData,
        //   invoceBill:billSn,
        invoceInfo: this.$refs.invoiceInfoList.tableData,
        paymentDetail:this.$refs.paymentDetails.tableData,
        // fileInfoIds: this.$refs.attachment.uploadIds
        // fileReqBOS: this.fileData
        files: this.fileData
      };
      tempSaveInvoceBasic(obj).then(res => {
        if (res.data.code == "0") {
          this.$message({
            type: "success",
            message: res.data.message,
            showClose: true,
            ccuiCustom: true,
            duration: 3000
          });
          this.$router.go(-1);
        }
      });
      this.fileData = [];
    },
    // 保存 提交
    submitHandle(name) {
      // this.getValidate(this.$refs.contractList.tableData);
      this.$refs.basicInfo.$refs.basicInfo.validate(valid => {
        if (valid) {
          // if (this.contractListBool) {
          // 调接口
          var totalAmount = Number(0);
          for (let i = 0; i < this.invoiceInfoList.length; i++) {
            totalAmount += Number(this.invoiceInfoList[i].priceTaxTotal);
          }
          this.basicForm.amount = totalAmount;
          let arrNum = this.$refs.attachment.fileList.length;
          for (let i = 0; i < arrNum; i++) {
            this.fileData[i] = {};
            this.fileData[i].uploadTime = this.$refs.attachment.fileList[
              i
            ].createTime;
            this.fileData[i].uploadId = this.$refs.attachment.fileList[
              i
            ].uploadId;
            this.fileData[i].fileDesc = this.$refs.attachment.fileList[
              i
            ].fileDesc;
          }
          if (name == "save") {
            this.saveInvoice();
          } else {
            this.submitInvoice();
          }
          // this.listPcConcSubByState();
          // this.listPcConcSubProtocolByState();
        } else {
          // 弹个窗
          this.$showErrorMessage("发票单基本信息不完整，请编辑后保存");
        }
      });
    },
    handleBack() {
      this.$router.push(
        sessionStorage.getItem("fromPath") || "/invoice/Entering/toSubmit"
      );
    },
    formatDateTime(date) {
      let _time = new Date(date);
      var y = _time.getFullYear();
      var m = _time.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = _time.getDate();
      d = d < 10 ? "0" + d : d;
      //   var h = _time.getHours();
      //   h = h < 10 ? "0" + h : h;
      return y + "-" + m + "-" + d;
    },
    saveInvoice() {
      let baseInfo = this.$refs.basicInfo.form;
      baseInfo = delete this.$refs.basicInfo.form.settlement;

      this.$refs.basicInfo.form.compileDate = this.basicFormDate; //时间重新赋值
      this.$refs.basicInfo.form.compileDate = this.formatDateTime(
        this.$refs.basicInfo.form.compileDate
      );

      this.$refs.basicInfo.form.settlement = baseInfo;
      // let invoiceDateInfo=this.$refs.invoiceInfoList.tableData.every(item=>{
      //     return item.invoiceDate;
      // })
      // console.log(invoiceDateInfo)
      // if(invoiceDateInfo==false){
      //     this.$showErrorMessage('发票信息开票日期必填')
      //     return;
      // }
      // if (this.$refs.invoiceInfoList.tableData) {
      //   this.$refs.invoiceInfoList.tableData.forEach((item, index) => {
      //     item.invoiceDate = this.formatDateTime(item.invoiceDate);
      //   });
      // }
      //ocr中ID如果是字符串传给后端会报错
      this.$refs.invoiceInfoList.tableData.forEach(e => {
        if (typeof e.id == "string") {
          delete e.id;
        }
      });

      this.$refs.basicInfo.form.compileDate = Date.parse(
        this.$refs.basicInfo.form.compileDate
      );
      this.$refs.invoiceBillList.tableData.forEach((e, index) => {
        e.sn = index;
        e.settlementListId = e.id;
        e.rate = e.taxRate;
      });
      this.$refs.paymentDetails.tableData.forEach(e=>{
        if(typeof e.id == 'string'){
          delete e.id;
        }
      })
      var obj = {
        invoceBasic: this.$refs.basicInfo.form,
        invoceBill: this.$refs.invoiceBillList.tableData,
        invoceInfo: this.$refs.invoiceInfoList.tableData,
        paymentDetail:this.$refs.paymentDetails.tableData,
        // fileInfoIds: this.$refs.attachment.fileList
        // fileReqBOS: this.fileData
        files: this.fileData
      };
      console.log(obj);
      saveInvoceBasic(obj).then(res => {
        this.$message({
          type: "success",
          message: res.data.message,
          showClose: true,
          ccuiCustom: true,
          duration: 3000
        });
        this.$router.go(-1);
      });
      this.fileData = [];
    },
    submitInvoice() {
      let baseInfo = this.$refs.basicInfo.form;
      baseInfo = delete this.$refs.basicInfo.form.settlement;

      this.$refs.basicInfo.form.compileDate = this.basicFormDate; //时间重新赋值

      this.$refs.basicInfo.form.settlement = baseInfo;
      this.$refs.invoiceBillList.tableData.forEach((e, i) => {
        e.contractBillId = e.materialId;
        e.settlementListId = e.id;
        e.sn = i;
        e.rate = e.taxRate;
      });
      // let invoiceDateInfo = this.$refs.invoiceInfoList.tableData.every(item=>{
      //     return item.invoiceDate;
      // })
      // console.log(invoiceDateInfo)
      // if(invoiceDateInfo == false){
      //     this.$showErrorMessage('发票信息开票日期必填')
      //     return;
      // }
      this.$refs.invoiceInfoList.tableData.forEach(e => {
        if (typeof e.id == "string") {
          delete e.id;
        }
      });
      this.$refs.paymentDetails.tableData.forEach(e=>{
        if(typeof e.id == 'string'){
          delete e.id;
        }
      })
      var obj = {
        invoceBasic: this.$refs.basicInfo.form,
        invoceBill: this.$refs.invoiceBillList.tableData,
        invoceInfo: this.$refs.invoiceInfoList.tableData,
        paymentDetail:this.$refs.paymentDetails.tableData,
        // fileInfoIds: this.$refs.attachment.uploadIds
        // fileReqBOS: this.fileData
        files: this.fileData
      };
      submitInvoice(obj).then(res => {
        this.$message({
          type: "success",
          message: res.data.message,
          showClose: true,
          ccuiCustom: true,
          duration: 3000
        });
        this.$router.go(-1);
      });
      this.fileData = [];
    },
    basicGetDate(basicGetDate) {
      this.basicFormDate = basicGetDate; //存储时间
    }
  },
  activated() {
    this.activeName = "a";
    this.invoiceBillList = [];
    this.$refs.invoiceInfoList.tableData = [];
    this.$refs.paymentDetails.tableData = [];
    this.fileList = [];
  },
  beforeRouteEnter(to, from, next) {
    !(to.fullPath === from.fullPath) &&
      sessionStorage.setItem("fromPath", from.fullPath);
    next();
  },
  // 更改列表缓存状态
  beforeRouteLeave(to, from, next) {
    // if (this.submitFlag === true) {
    for (var key in this.$vnode.parent.parent.componentInstance.cache) {
      delete this.$vnode.parent.parent.componentInstance.cache[
        ishasAgentId(to.path, key)
      ];
    }
    // }
    next();
  }
};
</script>

<style scoped lang="scss">
.commonClass {
  margin-top: 5px;
}

/deep/ .el-group-title .group-content {
  margin-top: 40px;
}
</style>
